﻿using System;
using System.Windows.Input;

namespace FlashCart.Core
{
    public class RelayCommand : ICommand
    {
        private Action<object> m_ExecuteMethod;

        public RelayCommand(Action<object> executeMethod)
            : this(executeMethod, true)
        { }

        public RelayCommand(Action<object> executeMethod, bool isExecutable)
        {
            if (executeMethod == null)
            {
                throw new ArgumentNullException("executeMethod");
            }

            m_ExecuteMethod = executeMethod;

            IsExecutable = isExecutable;
        }

        private bool m_IsExecutable;

        public bool IsExecutable
        {
            get { return m_IsExecutable; }
            set
            {
                if (value != m_IsExecutable)
                {
                    m_IsExecutable = value;
                    OnCanExecuteChanged();
                }
            }
        }

        public bool CanExecute(object parameter)
        {
            return m_IsExecutable;
        }

        public event EventHandler CanExecuteChanged;

        protected void OnCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        public void Execute(object parameter)
        {
            m_ExecuteMethod(parameter);
        }
    }
}
